//
//  Environment.m
//  ShopInMall_OC
//
//  Created by Sailer Guo on 2019/10/16.
//  Copyright © 2019 Sailer Guo. All rights reserved.
//

#import "Environment.h"
#import "SPCMSService.h"
#import "EnvironmentConstants.h"
#import <MJExtension/MJExtension.h>


NSString * const kMemberSid = @"shopin_memberSid";


@interface Environment ()

@property (nonatomic,nullable,strong,readwrite) HTTPService *apiService;
@property (nonatomic,nullable,strong,readwrite) SPPayService *payService;
@property (nonatomic,nullable,strong,readwrite) SPCMSService *cmsService;

@property (nonatomic,strong,readwrite) RACSubject *networkMonitoringSignal;

@property (nonatomic,assign,readwrite) EnvironmentType currentEnv;
@property (nonatomic,strong) AFNetworkReachabilityManager *networkMonitoring;

@end

@implementation Environment

+ (instancetype)sharedInstance {
    
    static Environment *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[Environment alloc] init];
    });
    
    return _instance;
}

- (instancetype)init {
    if (self = [super init]) {
        [self defaultEnv];
        
        // 检测网络变化
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        [manager startMonitoring];
        
        self.networkMonitoring = manager;
        
        @weakify(self)
        [self.networkMonitoring setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            @strongify(self)
            [self.networkMonitoringSignal sendNext:@(status)];
        }];
    }
    return self;
}

+ (NSTimeInterval)networkTimeout {
    return 30.0f;
}

// 切换主机地址
- (void)switchServiceEnv:(EnvironmentType)env {
    if (self.currentEnv == env) {
        return;
    }
    self.currentEnv = env;
    NSArray<id<SPService>> * services = @[self.apiService,self.payService,self.cmsService];
    
    for (id<SPService> service in services) {
        [service switchEnv:self.currentEnv];
    }
}

- (void)defaultEnv {
    
#ifdef DEV
    [self switchServiceEnv:Local];
#else
    [self switchServiceEnv:Production];
#endif
    
}

#pragma mark - Getters
- (HTTPService *)apiService {
    if (!_apiService) {
        _apiService = [[HTTPService alloc] init];
    }
    return _apiService;
}

- (SPPayService *)payService {
    if (!_payService) {
        _payService = [[SPPayService alloc] init];
    }
    return _payService;
}

- (SPCMSService *)cmsService {
    if (!_cmsService) {
        _cmsService = [[SPCMSService alloc] init];
    }
    return _cmsService;
}

- (RACSubject *)networkMonitoringSignal {
    if (!_networkMonitoringSignal) {
        _networkMonitoringSignal = [RACSubject subject];
    }
    return _networkMonitoringSignal;
}

#pragma mark - App 的基本信息
- (NSString *)appId {
    return @"1227592175";
}

- (NSString *)language {
    return @"zh_CN";
}

@end
